/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.cookor.poi.sys.interceptor;

import com.cookor.poi.common.config.Global;
import com.cookor.poi.common.service.BaseService;
import com.cookor.poi.common.utils.CookieUtils;
import com.cookor.poi.common.utils.IdGen;
import com.cookor.poi.common.utils.SpringContextHolder;
import com.cookor.poi.common.utils.UserAgentUtils;
import com.cookor.poi.modules.sys.utils.MobileUtils;
import com.cookor.poi.modules.weixin.account.Account;
import com.cookor.poi.modules.weixin.entity.TWeixinClinic;
import com.cookor.poi.modules.weixin.entity.TWeixinConfig;
import com.cookor.poi.modules.weixin.service.TWeixinClinicService;
import com.cookor.poi.modules.weixin.service.TWeixinConfigService;
import com.cookor.poi.utils.HttpUtils;
import com.google.common.collect.Maps;

import com.xiaoleilu.hutool.http.HttpUtil;
import com.xiaoleilu.hutool.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

/**
 * 手机端视图拦截器
 *
 * @author ThinkGem
 * @version 2014-9-1
 */
public class MobileInterceptor extends BaseService implements
        HandlerInterceptor {
	private static TWeixinConfigService weixinConfigService = SpringContextHolder
			.getBean(TWeixinConfigService.class);
	private static TWeixinClinicService weixinClinicService = SpringContextHolder
			.getBean(TWeixinClinicService.class);
//	private static WeixinUserService weixinUserService = SpringContextHolder
//			.getBean(WeixinUserService.class);
//	private static WeixinShareClickService weixinShareClickService = SpringContextHolder
//			.getBean(WeixinShareClickService.class);
//	private static IpFilterService ipFilterService = SpringContextHolder
//			.getBean(IpFilterService.class);

	/*
	 * 微信端访问必须先通过这个函数获取一些常用的变量如：openid、请求地址、客户端请求IP等
	 * 如果为微信第一次访问，先跳转至微信网页授权获取openid
	 */
	@Transactional(readOnly = false)
	public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession(true); // session
		MobileUtils.setSessionId(session.getId()); // 线程绑定sessionId
		String siteurl = HttpUtils.getVisitUrl(request); // 访问url
		Map<String, Object> requestMap = Maps.newConcurrentMap();
		Map<String, Object> sessionMap = MobileUtils
				.getSessionValue();
		String sessionUniacid = (String) sessionMap.get("uniacid");

		TWeixinConfig wc = null;
		Account account = null;
		TWeixinClinic clinic = null;
		String openid = null;
		String id = "";// 公账户ID(微信公众号配置id)
		String ip = HttpUtils.getClientIP(request);
		String siteId = request.getParameter("tenantId"); // 网点ID

		String token = IdGen.uuid();
		Date date = new Date();
		String uuid = IdGen.uuid();
		requestMap.put("uuid", uuid);// uuid;
		requestMap.put("token", token);// 用户处理重复提交
		requestMap.put("ispost", "POST".equals(request.getMethod()));// 是否为POST请求
		requestMap.put("isajax", HttpUtils.isAjax(request));// 是否为AJAX请求
		requestMap.put("timestamp", date.getTime());// 当前时间戳
		requestMap.put("clientip", ip);// 客户端IP
		requestMap.put("siteurl", siteurl);// 当前页面完整的URLhttp://www.nthink.cn/web/index.php?c=home&a=welcome&do=platform&
		requestMap.put("siteroot", HttpUtils.getSiteRoot(request));// 网站URL根目录http://www.nthink.cn/

		if (StringUtils.isNotBlank(siteId)) {
			requestMap.put("siteId", siteId);
//            clinic = weixinClinicService.get(siteId);
			wc = weixinConfigService.findByTenantId(Integer.valueOf(siteId));
			// 这里根据siteId拿到网点信息
//			requestMap.put("clinic", clinic);
//			id = clinic.getWeixinConfig().getId();
			id = wc.getId();
			account = Account.factory(id);
		}else{
			System.out.println("没有tenantId");
			return false;
		}
		// 如果是参与不同公众号活动，缓存要清空
		if (StringUtils.isBlank(sessionUniacid)) {
			sessionMap.put("uniacid", id);
		} else if (!StringUtils.equals(sessionUniacid, id)) {
			sessionMap.clear();
			MobileUtils.setSessionValue(sessionMap);
		}


		if (siteurl.indexOf("oauth") > -1) {
			MobileUtils.setRequstValue(requestMap);
			MobileUtils.setSessionValue(sessionMap);
			return true;
		}
//		if (!actionFilter(request, response, action, date, siteurl)) {// 是否播放广告
//			return false;
//		}
//		Fans fans = null;
//		if ("true".equals(Global.getDebug())) {// pc端测试
//			openid = request.getParameter("openid");
//			if (StringUtils.isBlank(openid)) {
//				System.out.println("调试模式参数openid不能为空！");
//				return false;
//			}
//			requestMap.put("uniacid", wc.getId());// 当前公众号id
//			requestMap.put("account", wc);// 当前公众号信息
//			sessionMap.put("uniacid", wc.getId());
//			WeixinUser user = weixinUserService.getByOpenid(openid);
//			fans = new Fans();
//			try {
//				BeanUtils.copyProperties(fans, user);
//			} catch (IllegalAccessException e) {
//				logger.warn(e.getMessage(), e);
//				e.printStackTrace();
//			}
//			sessionMap.put("fans", fans);
//			sessionMap.put("openid", user.getOpenid());
//			MobileUtils.setRequstValue(requestMap);
//			MobileUtils.setSessionValue(sessionMap);
//			return true;
//		}

		requestMap.put("jssdkconfig", account.getJssdkConfig(siteurl));
		requestMap.put("uniacid", wc.getId());// 当前公众号id
		requestMap.put("account", wc);// 当前公众号信息
		sessionMap.put("uniacid", wc.getId());
		if (siteurl.indexOf("oauth") == -1) {
			if (UserAgentUtils.isWeChat(request)) {// 判断s是否是微信访问
				openid = MobileUtils.getOpenid();
				if (StringUtils.isBlank(openid)) {// 如果没有openid跳转到微信接口获取
					sessionMap.put("dest_url",
							URLEncoder.encode(siteurl, "utf-8"));
					String scope = "";
//					if (action.getUserType() == 2) {
//						scope = "snsapi_userinfo";
//					}
					StringBuffer backurl = new StringBuffer();
					backurl.append(HttpUtils.getSiteRoot(request)
//							+ Global.getMobilePath());
							+ "/wx");
					backurl.append("/oauth");
					backurl.append("?siteId=");
					backurl.append(siteId);

//					if (StringUtils.isNotBlank(scope)) {
//						backurl.append("&scope=");
//						backurl.append(scope);
//					}
//					if (wc.isJiequan()) {// 订阅号有借权
//						account = Account.factory(wc.getOauthUniacid());
//						backurl.append("&i=");
//						backurl.append(wc.getOauthUniacid());
//						backurl.append("&OauthUniacid=" + wc.getId());
//					} else {
						backurl.append("&i=");
						backurl.append(id);
//					}
					if (account != null) {
						String url = account.getOauthCodeUrl(
								backurl.toString(), null, scope);
						MobileUtils.setRequstValue(requestMap);
						MobileUtils.setSessionValue(sessionMap);
						response.sendRedirect(url);
						return false;
					}
				} else {
					requestMap.put("openid", openid);
//					WeixinUser user = null;
//					fans = MobileUtils.getSessionFans();
//					if (fans == null) {
//						fans = new Fans();
//					}
//					if (wc.isJiequan()) {
//						if (fans == null
//								|| StringUtils.isBlank(fans.getUnionid())) {
//							System.out.println("订阅号需要与被借权公众号添加到同一个微信开发平台！");
//							return false;
//						}
//						user = weixinUserService.getByUnionid(wc.getAppid(),
//								fans.getUnionid());
//						if (user == null) {
//							user = new WeixinUser();
//							fans.setSubscribe("0");
//						}else{
//							fans.setSubscribe(user.getSubscribe());
//						}
//					} else {
//						JSONObject jo = account.getUserInfo(openid);
//						user = WeixinUserService.jsonToWeixinUser(jo);
//						if (action.getUserType() == 2
//								&& StringUtils.equals("0", user.getSubscribe())) {
//							fans.setSubscribe("0");
//						} else {
//							try {
//								BeanUtils.copyProperties(fans, user);
//							} catch (IllegalAccessException e) {
//								logger.warn(e.getMessage(), e);
//								e.printStackTrace();
//							}
//						}
//					}
//					requestMap.put("fans", fans);
				}
			}else{
				response.setContentType("text/html;charset=utf-8");
				response.setStatus(403);
				response.getWriter().write("请使用微信访问!");
				response.getWriter().flush();
				response.getWriter().close();
				return false;
			}
		}
		JSONObject userInfo = account.getUserInfo(openid);
		// 如果是点击朋友分享的保存点击记录begin
//		String sharer = request.getParameter("sharer");// 分享者openid
//		if (StringUtils.isNotBlank(sharer)) {
//			String shareId = request.getParameter("uuid");// 分享Id
//			requestMap.put("sharer", sharer);
//			WeixinShareClick weixinShareClick = new WeixinShareClick();
//			if (fans != null) {
//				weixinShareClick.setNickname(fans.getNickname());
//				weixinShareClick.setHeadimgurl(fans.getHeadimgurl());
//			}
//			weixinShareClick.setActionId(actionId);
//			weixinShareClick.setShareId(shareId);
//			weixinShareClick.setUrl(siteurl);
//			weixinShareClick.setSharer(sharer);
//			weixinShareClick.setOpenid(openid);
//			weixinShareClick.setActionId(actionId);
//			weixinShareClick.setProcessed(0);
//			weixinShareClickService.save(weixinShareClick);
//		}
		// 如果是点击朋友分享的保存点击记录end

		// 设置微信分享信息
//		Map<String, String> shareData = getShareData(action, siteurl, openid,
//				uuid);
//		requestMap.put("shareData", shareData);
		MobileUtils.setRequstValue(requestMap);
		MobileUtils.setSessionValue(sessionMap);
		return true;
	}

//	private Map<String, String> getShareData(WeixinAction action,
//                                             String siteurl, String openid, String uuid) {
//		Map<String, String> shareData = Maps.newConcurrentMap();
//		if (StringUtils.isNotBlank(action.getShareTitle())) {
//			shareData.put("title", action.getShareTitle());
//		}
//		if (StringUtils.isNotBlank(action.getShareDesc())) {
//			shareData.put("desc", action.getShareDesc());
//		}
//		String shareUrl = action.getShareUrl();
//		if (StringUtils.isNotBlank(shareUrl)) {
//			if (shareUrl.indexOf("?") != -1) {
//				shareUrl = shareUrl + "&sharer=" + openid + "&uuid=" + uuid;
//			} else {
//				shareUrl = shareUrl + "?sharer=" + openid + "&uuid=" + uuid;
//			}
//			shareData.put("link", shareUrl);
//		} else {
//			shareUrl = siteurl;
//			if (siteurl.indexOf("sharer=") != -1) {
//				shareUrl = StringUtils.replaceUrlPamasVal(shareUrl, "sharer",
//						openid);
//			} else {
//				shareUrl = siteurl + "&sharer=" + openid;
//			}
//			if (siteurl.indexOf("uuid=") != -1) {
//				shareUrl = StringUtils.replaceUrlPamasVal(shareUrl, "uuid",
//						uuid);
//			} else {
//				shareUrl = shareUrl + "&uuid=" + uuid;
//			}
//		}
//		shareData.put("link", shareUrl);
//		if (StringUtils.isNotBlank(action.getShareImg())) {
//			shareData.put("imgUrl", action.getShareImg());
//		}
//		return shareData;
//	}
//
//	private boolean actionFilter(HttpServletRequest request,
//                                 HttpServletResponse response, WeixinAction action, Date date,
//                                 String siteurl) throws IOException, ServletException {
//		if (action.getStartDt().getTime() < date.getTime()
//				&& StringUtils.isNotBlank(action.getUnbeginImg())) {// 活动未开始
//			request.getRequestDispatcher("actionUnbegin").forward(request,
//					response);
//		} else if (action.getEndDt().getTime() <= date.getTime()
//				&& StringUtils.isNotBlank(action.getOverImg())) {// 活动已经结束
//			request.getRequestDispatcher("actionOver").forward(request,
//					response);
//		}
//		if (action.getAdType() == null || action.getAdType() == 0) {
//			return true;
//		}
//		String key = action.getId();
//		String cookies = CookieUtils.getCookie(request, key);
//		if (StringUtils.isBlank(cookies)
//				|| Long.parseLong(cookies) < date.getTime()) {
//			String value = "";
//			// Integer time = action.getAdTime();
//			switch (action.getAdType()) {// 1：每次 2：每天 3：每周 4：仅1次）
//			case 1:
//				Map<String, Object> sessionMap = (Map<String, Object>) MobileUtils
//						.getSessionValue();
//				Object adFlag = sessionMap.get("adFlag");
//				if (adFlag != null
//						&& StringUtils.equals("1", adFlag.toString())) {
//					return true;
//				}
//				sessionMap.put("adFlag", "1");
//				MobileUtils.setSessionValue(sessionMap);
//				break;
//			case 2:
//				value = "" + DateUtil.offsiteDay(date, 1).getTime();
//				CookieUtils.setCookie(response, key, value, value);
//				break;
//			case 3:
//				value = "" + DateUtil.offsiteWeek(date, 1).getTime();
//				CookieUtils.setCookie(response, key, value, value);
//				break;
//			case 4:
//				value = "" + DateUtil.offsiteDay(date, 365).getTime();
//				CookieUtils.setCookie(response, key, value, value);
//				break;
//			}
//			request.setAttribute("dest_url", siteurl);
//			request.getRequestDispatcher("adIndex").forward(request, response);
//			return false;
//		}
//		return true;
//	}

	@Override
	public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
		if (modelAndView != null) {
			// View view = modelAndView.getView();
			Map<String, Object> map = MobileUtils.getRequestValue();
			if (map != null) {
				modelAndView.getModel().putAll(map);
			}
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

}
